"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 导入导出、备份恢复工具支持M*兼容性
Case Name   : 存储过程中调用时间类型函数，使用gs_dump导出后再执行导入
Create At   : 2023.05.04
Owner       : z@wan005
Description :
    1.创建兼容b库
    2.兼容b库创建测试用户并授权
    3.兼容b库创建存储过程，存储体使用时间类型函数
    4.使用gs_dump工具导出表为目录归档格式
    5.导入之前导出的数据到新库
    6.连接导入库查询并调用存储过程
    7.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.成功
    6.成功
    7.成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class GsDump0019(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.dbuser_node = Node('PrimaryDbUser')
        self.constant = Constant()
        self.com = Common()
        self.db_name = "db_dump_0019"
        self.db_name_01 = "db_dump_0019_01"
        self.pro_name = "pro_dump_0019"
        self.user_name = "user_dump0019"
        self.dump_path = os.path.join(macro.DB_BACKUP_PATH, 'dump0019')

    def test_server_tools(self):
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        text = '----step1: 创建兼容b库 expect: 成功----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"create database {self.db_name} encoding 'UTF8' " \
                  f"dbcompatibility 'b';" \
                  f"drop database if exists {self.db_name_01};" \
                  f"create database {self.db_name_01} encoding 'UTF8' " \
                  f"dbcompatibility 'b';"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd)
        self.log.info(sql_result)
        self.assertEqual(2, sql_result.count(
            self.constant.CREATE_DATABASE_SUCCESS), '执行失败:' + text)

        text = '---step2: 兼容b库创建测试用户并授权 expect: 成功---'
        self.log.info(text)
        sql_cmd = f'''drop user if exists {self.user_name} cascade;
        create user {self.user_name} password '{macro.PASSWD_INITIAL}';\
        grant proxy on current_user() to {self.user_name};'''
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname=self.db_name)
        self.log.info(sql_result)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, sql_result,
                      '执行失败:' + text)
        self.assertIn(self.constant.GRANT_SUCCESS_MSG, sql_result,
                      '执行失败:' + text)

        text = '--step3: 兼容b库创建存储过程，存储体使用时间类型函数 expect: 成功----'
        self.log.info(text)
        sql_cmd = f'''drop procedure if exists {self.pro_name};
        create definer = {self.user_name} procedure {self.pro_name}(
        date1 out date,
        date2 out date,
        date3 out date,
        maketime1 out time,
        value out int8,
        diff out int8,
        sec_to_time1 out time,
        subdate1 out text,
        subdate2 out text,
        subdate3 out time,
        subdate4 out time,
        subtime1 out text,
        subtime2 out text,
        time_1 out text,
        datetime1 out text,
        time_format1 out text,
        timediff1 out time,
        timediff2 out time,
        timestamp1 out datetime,
        timestamp2 out datetime,
        timestampadd1 out text,
        days out int8,
        seconds out int8,
        secondNum1 out numeric,
        secondNum2 out numeric,
        utc_date1 out date,
        utc_time1 out time,
        utc_time2 out time,
        utctimestamp1 out datetime,
        utctimestamp2 out datetime
    )
    IS
        BEGIN
            select makedate(2022, 31) into date1;
            select makedate(0, 31) into date2;
            select makedate(70, 32) into date3;
            select maketime(10, 10, 10) into maketime1;
            select period_add(202201, 2) into value;
            select period_diff(202201, 202003) into diff;
            select sec_to_time(4396) into sec_to_time1;
            select subdate('2022-01-01', interval 31 day) into subdate1;
            select subdate('2022-01-01', 31) into subdate2;
            select subdate(time'10:15:20', interval '1' day) into subdate3;
            select subdate(time'10:15:20', 1) into subdate4;
            select subtime('11:22:33', '10:20:30') into subtime1;
            select subtime('2020-03-04 11:22:33', '-10:20:30') into subtime2;
            select time('25:25:25') into time_1;
            select time('2022-1-1 1:1:1.1111116') into datetime1;
            select time_format('100:59:59', '%H|%k|%T|%I') into time_format1;
            select timediff(time'23:59:59', time'01:01:01') into timediff1;
            select timediff(datetime'2008-12-31 23:59:59', \
            datetime'2008-12-30 01:01:01') into timediff2;
            select timestamp('2022-01-01') into timestamp1;
            select timestamp('20000229', '100:00:00') into timestamp2;
            select timestampadd(day, 1, '2022-09-01') into timestampadd1;
            select to_days('0000-01-01') into days;
            select to_seconds('2022-09-01') into seconds;
            select unix_timestamp() into secondNum1;
            select unix_timestamp('2022-09-01') into secondNum2;
            select utc_date() into utc_date1;
            select utc_time() into utc_time1;
            select utc_time(6) into utc_time2;
            select utc_timestamp() into utctimestamp1;
            select utc_timestamp(6) into utctimestamp2;
        END;'''
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname=self.db_name)
        self.log.info(sql_result)
        self.assertIn(self.constant.CREATE_PROCEDURE_SUCCESS_MSG, sql_result,
                      '执行失败:' + text)

        text = '----step4: 使用gs_dump工具导出表为目录归档格式 expect: 成功----'
        self.log.info(text)
        gs_dump_cmd = f"source {macro.DB_ENV_PATH};" \
                      f"gs_dump " \
                      f"-p {self.dbuser_node.db_port} " \
                      f"{self.db_name} -F d " \
                      f"-f {self.dump_path}"
        self.log.info(gs_dump_cmd)
        dump_msg = self.dbuser_node.sh(gs_dump_cmd).result()
        self.log.info(dump_msg)
        self.assertIn(f"dump database {self.db_name} successfully",
                      dump_msg, '执行失败:' + text)

        text = '----step5: 导入之前导出的数据到新库 expect: 成功----'
        self.log.info(text)
        restore_cmd = f"source {macro.DB_ENV_PATH};" \
                      f"gs_restore -p {self.dbuser_node.db_port} " \
                      f"-d {self.db_name_01} {self.dump_path}"
        self.log.info(restore_cmd)
        restore_msg = self.dbuser_node.sh(restore_cmd).result()
        self.log.info(restore_msg)
        self.assertIn(self.constant.RESTORE_SUCCESS_MSG, restore_msg,
                      '执行失败:' + text)

        text = '-step6: 连接导入库查询并调用存储过程 expect: 成功--'
        self.log.info(text)
        sql_cmd = f"show create procedure {self.pro_name};" \
                  f"call {self.pro_name}(date1, date2, date3,time1,value," \
                  f"diff,sec_to_time1,subdate1,subdate2,subdate3,subdate4," \
                  f"subtime1,subtime2,time_1,datetime1,time_format1," \
                  f"timediff1,timediff2,timestamp1,timestamp2,timestampadd1," \
                  f"days,seconds,secondNum1,secondNum2,utc_date1,utc_time1," \
                  f"utc_time2,utctimestamp1,utctimestamp2);"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname=self.db_name_01)
        self.log.info(sql_result)
        self.assertIn(f'CREATE DEFINER = {self.user_name} PROCEDURE',
                      sql_result, '执行失败:' + text)
        self.assertIn('(1 row)', sql_result, '执行失败:' + text)
        self.assertIn(
            '2022-01-31 | 2000-01-31 | 1970-02-01 | 10:10:10  | 202203 |',
            sql_result)

    def tearDown(self):
        text = '---step7: 清理环境 expect: 成功----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"drop database if exists {self.db_name_01};" \
                  f"drop user if exists {self.user_name} cascade;"
        self.log.info(sql_cmd)
        sql_result = self.sh_primary.execut_db_sql(sql_cmd,
                                                   dbname='postgres')
        self.log.info(sql_result)
        rm_cmd = f"rm -rf {self.dump_path}"
        self.log.info(rm_cmd)
        rm_msg = self.dbuser_node.sh(rm_cmd).result()
        self.log.info(rm_msg)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, sql_result,
                      '执行失败:' + text)
        self.assertEqual(2,
                         sql_result.count(self.constant.DROP_DATABASE_SUCCESS))
        self.assertEqual('', rm_msg)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
